<template>
  <a-card
    :bordered="false"
    size="small"
    :bodyStyle="{
      overflow: 'auto',
      height: 'calc(100vh - 200px)',
    }"
  >
    <a-form-model
      :model="formData"
      :rules="rules"
      ref="myForm"
      :style="{ width: '100%' }"
      layout="vertical"
      v-bind="{}"
      :colon="true"
      labelAlign="right"
    >
      <a-row style="height: 100%">
        <a-col :span="24">
          <a-form-model-item prop="tableName" v-bind="{}">
            <span slot="label"
              >选择数据表<a style="margin-left:10px;" @click="getTables"
                ><a-icon type="reload"/></a
            ></span>
            <a-select
              v-model="formData.tableName"
              mode="default"
              :showSearch="true"
              placeholder=""
              size="default"
              :disabled="false"
              @change="getColumns"
            >
              <a-select-option
                v-for="(opt, idx) in tableName_options"
                :key="idx"
                :value="opt.tableName"
              >
                {{ opt.tableComment }}({{ opt.tableName }})
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item v-bind="{}">
            <span slot="label"
              >列配置<a style="margin-left:10px;" @click="getColumns"
                ><a-icon type="reload"/></a
            ></span>
            <a-table
              :pagination="false"
              size="small"
              :data-source="dataSource"
              :columns="columns"
            >
              <!-- 字段描述 -->
              <template slot="fieldNote" slot-scope="text, record">
                <a-input
                  size="small"
                  style="margin: -5px 0"
                  :value="text"
                  @change="
                    (e) => handleChange(e.target.value, record.key, 'fieldNote')
                  "
                />
              </template>
              <!-- 搜索条 -->
              <template slot="inSearch" slot-scope="text, record">
                <a-checkbox
                  size="small"
                  :defaultChecked="text"
                  @change="
                    (e) =>
                      handleChange(e.target.checked, record.key, 'inSearch')
                  "
                >
                </a-checkbox>
              </template>
              <!-- 列表 -->
              <template slot="inTable" slot-scope="text, record">
                <a-checkbox
                  size="small"
                  :defaultChecked="text"
                  @change="
                    (e) => handleChange(e.target.checked, record.key, 'inTable')
                  "
                >
                </a-checkbox>
              </template>
              <!-- 表单 -->
              <template slot="inForm" slot-scope="text, record">
                <a-checkbox
                  size="small"
                  :defaultChecked="text"
                  @change="
                    (e) => handleChange(e.target.checked, record.key, 'inForm')
                  "
                >
                </a-checkbox>
              </template>
              <!-- 表单类型 -->
              <template slot="formType" slot-scope="text, record">
                <a-select
                  style="width: 150px"
                  size="small"
                  :default-value="text"
                  @change="
                    (e) => {
                      handleChange(e, record.key, 'formType');
                    }
                  "
                >
                  <a-select-opt-group>
                    <span slot="label">基础</span>
                    <a-select-option value="text">
                      文本
                    </a-select-option>
                    <a-select-option value="textarea">
                      多行文本
                    </a-select-option>
                    <a-select-option value="number">
                      数字
                    </a-select-option>
                    <a-select-option value="password">
                      密码
                    </a-select-option>
                    <a-select-option value="radio">
                      单选
                    </a-select-option>
                    <a-select-option value="checkbox">
                      复选
                    </a-select-option>
                    <a-select-option value="select">
                      下拉
                    </a-select-option>
                    <a-select-option value="rate">
                      评分
                    </a-select-option>
                    <a-select-option value="time-picker">
                      时间
                    </a-select-option>
                    <a-select-option value="date-picker">
                      日期
                    </a-select-option>
                    <a-select-option value="range-picker">
                      日期范围
                    </a-select-option>
                    <a-select-option value="month-picker">
                      月份
                    </a-select-option>
                  </a-select-opt-group>
                  <a-select-opt-group>
                    <span slot="label">高级</span>
                    <a-select-option value="cascader">
                      级联下拉
                    </a-select-option>
                    <a-select-option value="treeSelect">
                      树形下拉
                    </a-select-option>
                    <a-select-option value="upload">
                      文件上传
                    </a-select-option>
                    <a-select-option value="tinymce">
                      富文本
                    </a-select-option>
                    <a-select-option value="tmap">
                      高德坐标拾取
                    </a-select-option>
                  </a-select-opt-group>
                  <a-select-opt-group>
                    <span slot="label">详情</span>
                    <a-select-option value="word">
                      文字
                    </a-select-option>
                    <a-select-option value="image">
                      图片
                    </a-select-option>
                    <a-select-option value="videoPlayer">
                      视频
                    </a-select-option>
                  </a-select-opt-group>
                </a-select>
              </template>
              <!-- 必填 -->
              <template slot="formRequired" slot-scope="text, record">
                <a-checkbox
                  size="small"
                  :defaultChecked="text"
                  @change="
                    (e) =>
                      handleChange(e.target.checked, record.key, 'formRequired')
                  "
                >
                </a-checkbox>
              </template>
            </a-table>
          </a-form-model-item>
        </a-col>
        <a-col :span='24'>
            <a-row :gutter='5'>
              <a-col :span='6'>
                <a-form-model-item label='项目跟路径' prop='projectPath' v-bind='{}'>
                  <a-input v-model='formData.projectPath' placeholder='' :allowClear='true' size='default'
                    :disabled='false'></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span='6'>
                <a-form-model-item label='模块名称' prop='modelName' v-bind='{}'>
                  <a-input v-model='formData.modelName' placeholder='' :allowClear='true' size='default'
                    :disabled='false'></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span='6'>
                <a-form-model-item label='跟映射地址' prop='requestMapping' v-bind='{}'>
                  <a-input v-model='formData.requestMapping' placeholder='' :allowClear='true' size='default'
                    :disabled='false'></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span='6'>
                <a-form-model-item label='开发者' prop='author' v-bind='{}'>
                  <a-input v-model='formData.author' placeholder='' :allowClear='true' size='default'
                    :disabled='false'></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
        <a-col :span="24">
          <a-form-model-item :wrapper-col="{ span: 20, offset: 0 }">
            <a-button
              style="margin-right:10px"
              type="primary"
              @click="handleTableDesign"
            >
              表格设计
            </a-button>
            <a-button
              style="margin-right:10px"
              type="primary"
              @click="handleFormDesign"
            >
              表单设计
            </a-button>
            <a-button
              style="margin-right:10px"
              type="primary"
              @click="handleDetailDesign"
            >
              详情页设计
            </a-button>
             <a-button
              style="margin-right:10px"
              :loading="confirmLoading"
              type="primary"
              @click="handleOk"
            >
              生成
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <form-design ref='formDesign' @success="formDone"/>
    <table-design ref="tableDesign" @success="tableDone"/>
    <detail-design ref="detailDesign" @success="detailDone"/>
  </a-card>
</template>

<script>
import { formTemplate } from './util/dform'
import { tableTemplate } from './util/dTable'
import storage from 'store'
import { getTableInfos, getColumnInfos, createLocalPage } from '@/api/generator'
import FormDesign from './formDesign.vue'
import TableDesign from './tableDesign'
import DetailDesign from './detailDesign'

export default {
  components: { FormDesign, TableDesign, DetailDesign },
  props: [],
  data() {
    return {
      dataSource: [],
      columns: [
        {
          title: '字段名称',
          dataIndex: 'fieldName',
          align: 'left'
        },
        {
          title: '字段类型',
          dataIndex: 'fieldType',
          align: 'left'
        },
        {
          title: '字段描述',
          dataIndex: 'fieldNote',
          scopedSlots: { customRender: 'fieldNote' },
          align: 'left'
        },
        {
          title: '搜索条',
          dataIndex: 'inSearch',
          scopedSlots: { customRender: 'inSearch' },
          align: 'center'
        },
        {
          title: '列表',
          dataIndex: 'inTable',
          scopedSlots: { customRender: 'inTable' },
          align: 'center'
        },
        {
          title: '表单',
          dataIndex: 'inForm',
          scopedSlots: { customRender: 'inForm' },
          align: 'center'
        },
        {
          title: '表单类型',
          dataIndex: 'formType',
          scopedSlots: { customRender: 'formType' },
          align: 'center'
        },
        {
          title: '必填',
          dataIndex: 'formRequired',
          scopedSlots: { customRender: 'formRequired' },
          align: 'center'
        }
      ],
      confirmLoading: false,
      defaultFormData: {
        tableName: '',
        projectPath: '',
        modelName: '',
        author: '',
        requestMapping: ''
      },
      formData: {},
      rules: {
        requestMapping: [{
          required: true,
          message: '项目跟映射不能为空',
          trigger: 'blur'
        }, {
          max: 50,
          message: '项目跟映射最大长度不能大于50',
          trigger: 'blur'
        }],
        tableName: [
          {
            required: true,
            message: '选择表不能为空',
            trigger: 'change'
          }
        ],
        projectPath: [{
          required: true,
          message: '项目跟路径不能为空',
          trigger: 'blur'
        }, {
          max: 100,
          message: '项目跟路径最大长度不能大于100',
          trigger: 'blur'
        }],
        modelName: [{
          required: true,
          message: '模块名称不能为空',
          trigger: 'blur'
        }, {
          max: 20,
          message: '模块名称最大长度不能大于20',
          trigger: 'blur'
        }],
        author: [{
          required: true,
          message: '开发者不能为空',
          trigger: 'blur'
        }, {
          max: 20,
          message: '开发者最大长度不能大于20',
          trigger: 'blur'
        }]
      },
      tableName_options: [],
      formDesign: null,
      tableDesign: null,
      detailDesign: null
    }
  },
  computed: {},
  watch: {},
  created() {
    this.formData = Object.assign({}, this.defaultFormData)
  },
  mounted() {
    this.init()
  },
  methods: {
    /* 表单设计完成 */
    formDone(c) {
      this.formDesign = c
    },
    /* table设计完成 */
    tableDone(c) {
      this.tableDesign = c
    },
    /* 表单设计 */
    handleFormDesign() {
      if (this.formDesign != null) {
        this.$refs.formDesign.showHistory(this.formDesign.widgetList, this.formDesign.formConf)
      } else {
        this.$refs.formDesign.showModal(this.dataSource)
      }
    },
    /* 表格设计 */
    handleTableDesign() {
      if (this.tableDesign != null) {
        this.$refs.tableDesign.showHistory(this.tableDesign)
      } else {
        this.$refs.tableDesign.showModal(this.dataSource)
      }
    },
    /* 详情页设计 */
    handleDetailDesign() {
      if (this.detailDesign != null) {
        this.$refs.detailDesign.showHistory(this.detailDesign.widgetList, this.formDesign.formConf)
      } else {
        this.$refs.detailDesign.showModal(this.dataSource)
      }
    },
    detailDone(d) {
      console.log(d)
      this.detailDesign = d
    },
    /* 列配置修改 */
    handleChange(value, key, column) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => key === item.key)[0]
      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },
    init() {
      this.getTables()
    },
    getTables() {
      const data = storage.get('datasource')
      if (data) {
        getTableInfos(data).then((res) => {
          if (res.code === 1) {
            this.tableName_options = res.data
            this.$message.success('加载完成')
          } else {
            this.tableName_options = []
          }
        })
      } else {
        this.$message.error('请先配置数据源')
      }
    },
    getColumns() {
      this.$nextTick(() => {
        const data = storage.get('datasource')
        Object.assign(data, {
          tableName: this.formData.tableName
        })
        if (data) {
          if (this.formData.tableName) {
            getColumnInfos(data).then((res) => {
              if (res.code === 1) {
                const data = res.data
                const dataSource = []
                data.forEach((d, idx) => {
                  dataSource.push({
                    key: idx,
                    fieldName: d.propertyName,
                    fieldType: d.javaType,
                    fieldNote: d.columnComment,
                    inSearch: false,
                    inTable: true,
                    inForm: true,
                    formType: 'text',
                    formRequired: true
                  })
                })
                this.dataSource = dataSource
                this.formDesign = null
                this.tableDesign = null
                this.detailDesign = null
                this.$message.success('加载完成')
              } else {
                this.dataSource = []
              }
            })
          } else {
            this.$message.error('请先选择数据库表')
          }
        } else {
          this.$message.error('请先配置数据源')
        }
      })
    },
    handleOk() {
      // this.confirmLoading = true
      this.$refs['myForm'].validate((valid) => {
        if (!valid) {
          console.log('error')
          this.confirmLoading = false
        } else {
          // TODO 提交表单
          if (this.tableDesign == null) {
            this.$message.error('请先设计表格')
            this.confirmLoading = false
            return
          }
          if (this.formDesign == null) {
            this.$message.error('请先设计表单')
            this.confirmLoading = false
            return
          }
          if (this.detailDesign == null) {
            this.$message.error('请先设计详情')
            this.confirmLoading = false
            return
          }
          createLocalPage({
            detailVue: formTemplate(this.detailDesign),
            editVue: formTemplate(this.formDesign),
            indexVue: tableTemplate(this.tableDesign),
            projectPath: this.formData.projectPath,
            modelName: this.formData.modelName,
            author: this.formData.author,
            tableName: this.formData.tableName,
            requestMapping: this.formData.requestMapping
          }).then(res => {
            if (res.code === 1) {
              this.$message.success('操作成功')
            }
          })
          this.confirmLoading = false
        }
      })
    },
    onReset() {
      this.$refs['myForm'].resetFields()
      this.hideModal()
    }
  }
}
</script>
<style scoped lang="less">
/*复选框样式*/
.ant-checkbox-wrapper + .ant-checkbox-wrapper {
  margin-left: 0px;
}
</style>
